<template>
	<div class="text-center h-80">
		<el-form :model="form" :rules="rules" ref="formRef" class="mt-20">
			<el-form-item prop="email">
				<el-input v-model="form.email" placeholder="邮箱" />
			</el-form-item>
			<el-form-item prop="password">
				<el-input v-model="form.password" placeholder="密码" />
			</el-form-item>

			<el-button class="w-full" type="primary" @click="submit">登录</el-button>

			<div
				class="mx-auto mt-4 border w-24 border-gray-300 rounded-3xl p-2 cursor-pointer hover:bg-gray-100"
				@click="handleGoogleLogin"
			>
				Google
			</div>
		</el-form>
	</div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores'
import { GOOGLE_LOGIN_URL, login } from '@/api'
import { MD5 } from 'crypto-js'

const userStore = useUserStore()

interface FormType {
	email: string
	password: string
}

const formRef = ref<FormInstance>()

const form = ref<FormType>({
	email: '',
	password: '',
})

const rules = reactive<FormRules<FormType>>({
	email: {
		required: true,
		message: '请输邮箱',
		trigger: 'blur',
	},
	password: {
		required: true,
		message: '请输入密码',
		trigger: 'blur',
	},
})

const submit = async () => {
	const valid = await formRef.value?.validate()
	if (!valid) return

	const res = await login({
		email: form.value.email,
		password: MD5(form.value.password).toString(),
	})

	if (res.msg) {
		ElMessage.error(res.msg)
		return
	}

	localStorage.setItem('token', res.access_token)
	localStorage.setItem('refresh_token', res.refresh_token)

	location.reload()
}

const handleGoogleLogin = async () => {
	window.location.href = GOOGLE_LOGIN_URL
}

defineExpose({
	submit,
})
</script>

<style scoped lang="scss"></style>
